package data.deal;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import dataconnect.ConnectionFactory;
import dataconnect.SqlUtil;

public class CompanyResult {
	public void deal(String code){
		Document doc = null;
		try {
			doc = Jsoup.connect("http://stockhtm.finance.qq.com/sstock/ggcx/"+code.substring(2, code.length())+".shtml").get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(doc==null){
			return;
		}
		
		String score="0";
		String idealPrice="0";
		Elements els = doc.getElementsByClass("nob");
		for (Element element : els) {
			Elements els2 = element.getElementsByClass("col-2");
			for (Element element2 : els2) {
				System.out.println(code);
				score=element2.text();
				break;
			}
		}
		
		Elements scriptE = doc.getElementsByTag("script");
		
		for (Element element : scriptE) {
			String str = element.data();
			if(str.indexOf("var g_StockRating")>=0){
				String[] varStr = str.split(",");
				for (int i = 0; i < varStr.length; i++) {
					if(varStr[i].indexOf("expect_price:")>=0){
						idealPrice = varStr[i].substring(14, varStr[i].length()-1);
						if(!isNum(idealPrice)){
							idealPrice="0";
						}
						break;
					}
				}
			}
		}
		
			System.out.println(score+","+idealPrice);
		SqlUtil.update("update stockanlyz set score="+score+",idealPrice="+idealPrice+" where number ='"+code+"'");
	}
	
	private boolean isNum(String str){
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}
	
	public static void main(String[] args) {
		CompanyResult cr = new CompanyResult();
		String sql = "select number from stockinfo where number not in ('sh000001','sz399001') ";
		Connection con = ConnectionFactory.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()){
				String code = rs.getString(1);
				
				cr.deal(code);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null){
					rs.close();
				}
				if(stmt!=null){
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
